* Table 5 Impact of number of years of insurance coverage : sample used to study investments and agricultural outcomes
* Last Updated, Niriksha Shetty 03/31/206

clear
clear mata
clear matrix
set maxvar 20000
set more off

pwd
cap cd c(`pwd')

estimates clear

use "../dta/reduced-form-master.dta", clear

*Using balanced panel
keep if bal_panel3==1

sort id mkt_year

local uniqinst "bdmperc_20* fourbdmperc_20* disc4game_20* assigned_risk_ws_2008 assigned_risk_ws_2010 assigned_video_test assigned_drought_flyer assigned_subsidies_flyer assigned_loan discount_20* rebate_50percentoff rebate2_1free rebate3_1free flyer_hyv sewaT peerT ppayT vframeT pframeT groupT muslimT hinduT " /* assigned_risk_ws_2011 assigned_risk_ws_2012 assigned_risk_ws_2013 mrkt_allnegative mrkt_poslang mrkt_posimg*/

foreach var of varlist `uniqinst' {
	replace `var' = 0 if treat_year==0
}

* creating cumulative individual treatment variables
foreach x of varlist `uniqinst' {
replace `x'=. if `x'==0
bys id : carryforward `x', gen(`x'_ally)
}

foreach var of varlist `uniqinst' *_ally {
	replace `var' = 0 if `var'==.
	replace `var' = 0 if wave==0
}

* creating table
local table = 1
local rastring "replace"
local outcomevars "totalrevenues_w1_real kval_w1_real fin_revenues_real totalcosts_w1_real cost_k_w1_real b110rk_w1_real b111rk_w1_real b112pk_w1_real total_mandays_k_w1 total_hired_mandays_k_w1 total_fam_mandays_k_w1 fin_costs_real totalprofit_w1_real profit_k_w1_real  fraction_hy fraction_cashcrop plotsize_ha"

foreach var of local outcomevars {
replace `var' = 0 if `var' == .
}

* creating cumulative policy units purchased
by id: gen cs_policy_units = sum(s_policy_units)
gen Dpurch = (s_policy_units>0)
by id: gen cDpurch = sum(Dpurch)

foreach ovar of varlist `outcomevars' {
local col=1
	di "`ovar'"
	di "`table'"

	/* Village IV (No Fixed Effects) */
	ivreg2 `ovar' (cs_policy_units=treat_year) year2*  firstt_2007  resurveyed lost_w3 , r cluster(villageno) 
	estimates store cT`table'C`col++'

	/* Village IV(FE/RE) */
	xtivreg2 `ovar' (cs_policy_units=treat_year) year2*  firstt_2007 resurveyed lost_w3 , fe cluster(villageno)
	estimates store cT`table'C`col++'
	
	/* IND IV (No Fixed Effects) */
	ivreg2 `ovar' (cs_policy_units=treat_year *_ally) year2*  firstt_2007 lost_w3 resurveyed  , r cluster(villageno) 
	estimates store cT`table'C`col++'
	
	/* IND IV (Individual FE/RE) */
	xtivreg2 `ovar' (cs_policy_units=treat_year *_ally) year2*  firstt_2007 lost_w3 resurveyed , fe cluster(villageno)
	estimates store cT`table'C`col++'	

	qui estout cT`table'C* using "../output/t5.csv", ///
	cells(b(star fmt(3)) se(par(`"="("' `")""'))  ) stardetach  delimiter(",") ///
	starlevels(* .1 ** .05 *** .01) ///
	keep (cs_policy_units) prehead("`ovar'") ///
	mlabel("" "" "" "") ///
	`rastring' label stats(cdf N) 

local rastring "append"

}
